<?php

class Application_Controller_Helper_Login extends Zend_Controller_Action_Helper_Abstract{
    
    public function preDispatch()
    {
        $view = $this->getActionController()->view;
        $form = new Application_Form_FLogowanie();

        $request = $this->getActionController()->getRequest();
        if($request->isPost()){
            if($form->isValid($request->getPost())){                
                //sprawdzamy czy dane dostępowe podane w formularzu zgadzaja sie z tymi w bazie danych
                $adapter = $this->getAuthAdapter($form->getValues());
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($adapter);
                
               if($result->isValid()){                                                        
                    $storage = $auth->getStorage();
                    $storage->write($adapter->getResultRowObject(
                        array('USE_id', 'USE_login', 'USE_typ')));             
               }
            }
        }        
        $view->logowanieForm = $form;
    }
    
    //do adaptera przekazuje parametry pobrane z formularza logowania
    public function getAuthAdapter(array $aParams){

        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $oAuthAdapter = new Zend_Auth_Adapter_DbTable($db, 'user', 'USE_login', 'USE_password');
        $oAuthAdapter->setIdentity($aParams['login']);
        $oAuthAdapter->setCredential($aParams['password']);
        
        return $oAuthAdapter;
    }
}

